"""Enable custom account types

Revision ID: d08d0b37788a
Revises: 0ae4ef82b244
Create Date: 2016-05-19 18:36:18.693108

"""

# revision identifiers, used by Alembic.
revision = 'd08d0b37788a'
down_revision = 'ad23a56abf25'

from alembic import op
import sqlalchemy as sa

from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


Session = sessionmaker()
Base = declarative_base()


class Account(Base):
    __tablename__ = 'account'
    id = sa.Column(sa.Integer, primary_key=True)
    account_type_id = sa.Column(sa.Integer())
    number = sa.Column(sa.String())
    identifier = sa.Column(sa.String())


class AccountType(Base):
    __tablename__ = 'account_type'
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column('name', sa.String(length=80))


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('account_type',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=80), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('name')
    )
    op.create_table('account_type_values',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=64), nullable=True),
    sa.Column('value', sa.String(length=256), nullable=True),
    sa.Column('account_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['account_id'], ['account.id'], ),
    sa.PrimaryKeyConstraint('id')
    )

    bind = op.get_bind()
    session = Session(bind=bind)

    account_type = AccountType(name='AWS')
    session.add(account_type)
    session.commit()

    op.add_column(u'account', sa.Column('account_type_id', sa.Integer(), nullable=False, server_default=str(account_type.id)))
    op.add_column(u'account', sa.Column('identifier', sa.String(length=256), nullable=True))
    op.create_foreign_key('account_account_type_id_fkey', 'account', 'account_type', ['account_type_id'], ['id'])
    op.create_unique_constraint('account_name_uc', 'account', ['name'])
    ### end Alembic commands ###

    accounts = session.query(Account).all()
    for account in accounts:
        account.identifier = account.number
        session.add(account)

    session.commit()


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('account_account_type_id_fkey', 'account', type_='foreignkey')
    op.drop_column(u'account', 'identifier')
    op.drop_column(u'account', 'account_type_id')
    op.drop_table('account_type_values')
    op.drop_table('account_type')
    op.drop_constraint('account_name_uc', 'account', type_='unique')
    ### end Alembic commands ###
